/*
 * MIT License
 *
 * Copyright (c) 2024-2048 冰羽
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.star.framework.code;

import cn.hutool.core.util.StrUtil;
import groovy.lang.GroovyClassLoader;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Java源码管理<br>
 *
 * @author zhaoweiping
 *     <p style='color: red'>Created on 2024-09-23 11:06:00
 * @since 3.0.0
 */
public abstract class AbstractJavaSourceManager {

  /** groovy class loader */
  protected GroovyClassLoader groovyClassLoader = new GroovyClassLoader();

  protected ConcurrentMap<String, Class<?>> classCache = new ConcurrentHashMap<>();

  /**
   * 从源码中加载出一个类
   *
   * @param codeSource 源码
   * @return
   * @throws Exception
   */
  public Class<?> loadClass(String codeSource) throws Exception {
    if (StrUtil.isNotEmpty(codeSource)) {
      // 无需缓存
      Class<?> clazz = groovyClassLoader.parseClass(codeSource);
      return clazz;
    }

    throw new IllegalArgumentException(
        ">>>>>>>>>>>>>>>>> java-source-manager, load class error, 源代码不存在");
  }

  /**
   * 从源码中加载出一个类（内部缓存）
   *
   * @param codeSource 源码
   * @return 源码Class
   */
  public Class<?> getCodeSourceClass(String codeSource) {
    try {
      byte[] algorithm = MessageDigest.getInstance(getAlgorithm()).digest(codeSource.getBytes());
      String algorithmStr = new BigInteger(1, algorithm).toString(16);

      Class<?> clazz = classCache.get(algorithmStr);
      if (clazz == null) {
        clazz = loadClass(codeSource);
        classCache.putIfAbsent(algorithmStr, clazz);
      }
      return clazz;
    } catch (Exception e) {
      return groovyClassLoader.parseClass(codeSource);
    }
  }

  /**
   * 获取加密算法 可使用的值有 [MD2\MD5\SHA-1\SHA-256\SHA-384\SHA-512] {@link AlgorithmType}
   *
   * @return 加密规则
   */
  protected String getAlgorithm() {
    return AlgorithmType.MD5.getValue();
  }
}
